package flc.ast.activity;

import android.Manifest;
import android.view.View;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.stark.picselect.PhotoSelectorBuilder;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.interfaces.OnSelectResultListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.AlbumPicAdapter;
import flc.ast.bean.Album;
import flc.ast.bean.AlbumPicBean;
import flc.ast.bean.Image;
import flc.ast.dataBase.AppDatabase;
import flc.ast.databinding.ActivityAlbumBinding;
import flc.ast.dialog.AddLabelDialog;
import flc.ast.utils.ImageLocationUtils;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class AlbumActivity extends BaseAc<ActivityAlbumBinding> implements OnItemLongClickListener {

    public static Album album;
    private boolean isEdit;
    private boolean isLongClick;
    private List<AlbumPicBean> listShow = new ArrayList<>();
    private AlbumPicAdapter albumPicAdapter;
    private List<Image> listSel = new ArrayList<>();
    private Image selImage;

    @Override
    protected int onCreate() {
        return R.layout.activity_album;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivAlbumBack.setOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());

        getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                if (isEdit || isLongClick) {
                    isEdit = false;
                    isLongClick = false;
                    mDataBinding.ivAdd.setVisibility(View.VISIBLE);
                    mDataBinding.tvDelete.setVisibility(View.GONE);
                    mDataBinding.llEdit.setVisibility(View.GONE);
                    getData();
                } else {
                    finish();
                }
            }
        });

        mDataBinding.ivAlbumEdit.setOnClickListener(this);
        mDataBinding.ivAdd.setOnClickListener(this);
        mDataBinding.tvDelete.setOnClickListener(this);
        mDataBinding.tvEditDelete.setOnClickListener(this);
        mDataBinding.tvLabel.setOnClickListener(this);
        mDataBinding.llCollect.setOnClickListener(this);
        mDataBinding.tvRemove.setOnClickListener(this);
        mDataBinding.tvShare.setOnClickListener(this);

        mDataBinding.rvPictureList.setLayoutManager(new GridLayoutManager(mContext, 3));
        albumPicAdapter = new AlbumPicAdapter();
        mDataBinding.rvPictureList.setAdapter(albumPicAdapter);
        albumPicAdapter.setOnItemClickListener(this);
        albumPicAdapter.setOnItemLongClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        int id = v.getId();
        if (id == R.id.ivAlbumEdit) {//删除编辑
            if (isLongClick || isEdit) return;
            isEdit = true;
            mDataBinding.tvDelete.setText(getString(R.string.delete_num, listSel.size()));
            mDataBinding.ivAdd.setVisibility(View.GONE);
            mDataBinding.tvDelete.setVisibility(View.VISIBLE);
        } else if (id == R.id.ivAdd) {//添加图片
            getPermission();
        } else if (id == R.id.tvDelete) {//多选删除
            if (listSel.size() == 0) return;
            for (Image image : listSel) {
                AppDatabase.getInstance(mContext).albumDao().deleteImage(image);
            }
            listSel.clear();
            mDataBinding.tvDelete.setText(getString(R.string.delete_num, listSel.size()));
            ToastUtils.showShort(getString(R.string.delete_suc));
            getData();
        } else if (id == R.id.tvEditDelete || id == R.id.tvRemove) {//删除/移出
            AppDatabase.getInstance(mContext).albumDao().deleteImage(selImage);
            mDataBinding.ivAdd.setVisibility(View.VISIBLE);
            mDataBinding.llEdit.setVisibility(View.GONE);
            ToastUtils.showShort(getString(R.string.delete_suc));
            getData();
        } else if (id == R.id.tvLabel) {//标签
            showAddLabelDialog();
        } else if (id == R.id.llCollect) {//收藏
            selImage.isFavorite = !selImage.isFavorite;
            AppDatabase.getInstance(mContext).albumDao().updateImage(selImage);
            isCollect();
        } else if (id == R.id.tvShare) {//分享
            IntentUtil.shareImage(mContext, "", selImage.path);
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (isEdit) {
            if (albumPicAdapter.getItem(position).isSelected()) {
                albumPicAdapter.getItem(position).setSelected(false);
                listSel.remove(albumPicAdapter.getItem(position).getImage());
            } else {
                albumPicAdapter.getItem(position).setSelected(true);
                listSel.add(albumPicAdapter.getItem(position).getImage());
            }
            mDataBinding.tvDelete.setText(getString(R.string.delete_num, listSel.size()));
            albumPicAdapter.notifyItemChanged(position);
        } else {
            ImageDetailActivity.image = albumPicAdapter.getItem(position).getImage();
            startActivity(ImageDetailActivity.class);
        }
    }

    @Override
    public boolean onItemLongClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (!isEdit) {
            isLongClick = true;
            albumPicAdapter.getItem(position).setSelected(true);
            albumPicAdapter.notifyItemChanged(position);
            selImage = albumPicAdapter.getItem(position).getImage();
            mDataBinding.ivAdd.setVisibility(View.GONE);
            mDataBinding.llEdit.setVisibility(View.VISIBLE);
            isCollect();
        }
        return false;
    }

    @Override
    protected void initData() {
        mDataBinding.tvAlbumName.setText(album.name);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    private void getData() {
        listShow.clear();
        List<Image> list = AppDatabase.getInstance(mContext).albumDao().getImagesByAlbumId(album.id);
        if (list != null && list.size() != 0) {
            for (Image image : list) {
                listShow.add(new AlbumPicBean(image));
            }
            albumPicAdapter.setList(listShow);
            mDataBinding.rvPictureList.setVisibility(View.VISIBLE);
            mDataBinding.tvPictureNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvPictureList.setVisibility(View.GONE);
            mDataBinding.tvPictureNoData.setVisibility(View.VISIBLE);
        }
    }

    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO, Manifest.permission.ACCESS_MEDIA_LOCATION)
                .reqPermissionDesc(getString(R.string.get_picture_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        getImage();
                    }
                }).request();
    }

    private void getImage() {
        PhotoSelectorBuilder.builder(this)
                .mode(PhotoConfig.Mode.PHOTO)
                .minCount(1)
                .maxCount(9)
                .listener(new OnSelectResultListener<List<SelectMediaEntity>>() {
                    @Override
                    public void onResult(List<SelectMediaEntity> data) {
                        ArrayList<String> pathList = new ArrayList<>();
                        for (SelectMediaEntity entity : data) {
                            pathList.add(entity.getTargetPath());
                        }
                        for (String path : pathList) {
                            Image image = new Image();
                            image.albumId = album.id;
                            image.path = path;
                            image.isFavorite = false;
                            String city = ImageLocationUtils.getCityFromImage(mContext, path);
                            image.city = city == null ? getString(R.string.other_text) : city;
                            image.time = FileUtils.getFileLastModified(path);
                            AppDatabase.getInstance(mContext).albumDao().insertImage(image);
                        }
                        getData();
                    }
                });
    }

    private void showAddLabelDialog() {
        AddLabelDialog dialog = new AddLabelDialog(mContext);
        dialog.setName(selImage.tags);
        dialog.setListener(new AddLabelDialog.Listener() {
            @Override
            public void clickConfirm(String name) {
                selImage.tags = name;
                AppDatabase.getInstance(mContext).albumDao().updateImage(selImage);
            }
        });
        dialog.show();
    }

    private void isCollect() {
        mDataBinding.ivCollect.setImageResource(selImage.isFavorite ? R.drawable.aysc : R.drawable.awsc);
    }

}